//
//  SoapArgs.m
//  wsdlWebService
//
//  Created by wulanzhou on 2017/10/11.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

#import "SoapArgs.h"

@implementation SoapArgs

- (instancetype)init{

    if (self = [super init]) {
        self.soapHeader = [[SoapHeader alloc] init];
        self.soapBody = [[SoapBody alloc] init];
        self.httpWay = RequestMethodPost;
    }
    return self;
}

//
- (NSMutableURLRequest *)request{
    
    //1.确定请求的URL地址
    NSURL *url = [NSURL URLWithString:self.serviceUrlStr];
    
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSString *bodyData = [self requestBody];
    
    //3.请求头
    [request setAllHTTPHeaderFields:[self requestHeaderWithLength:[bodyData length]]];
    
    //4.请求方法
    if(self.httpWay == RequestMethodGet){
       [request setHTTPMethod:@"GET"];
    }else if(self.httpWay == RequestMethodPost){
       [request setHTTPMethod:@"POST"];
    }else if(self.httpWay == RequestMethodPut){
        [request setHTTPMethod:@"PUT"];
    }else if(self.httpWay == RequestMethodDelete){
        [request setHTTPMethod:@"DELETE"];
    }
    
    //5.设置超时时间
    [request setTimeoutInterval:30.0f];
    
    //6.设置body
    [request setHTTPBody:[bodyData dataUsingEncoding:NSUTF8StringEncoding]];
    

    return request;
}

#pragma mark -请求body
//私有方法
- (NSString *)requestBody{

    NSMutableString *r_body = [NSMutableString stringWithString:@"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservices.energyspace\">"];
    //soap header
    [r_body appendString:[self.soapHeader soapHeaderString]];
    //soap body
    [r_body appendString:[self.soapBody soapBodyString]];
    
    [r_body appendString:@"</soapenv:Envelope>"];
    
    NSLog(@"请求参数: %@",r_body);
    
    return r_body;

}

-(NSDictionary*)requestHeaderWithLength:(NSUInteger)length{
    
    NSURL *url = [NSURL URLWithString:self.serviceUrlStr];
    if (self.httpWay==RequestMethodGet) {
        
        return [NSMutableDictionary dictionaryWithObjectsAndKeys:[url host],@"Host", nil];
    }
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setValue:[url host] forKey:@"Host"];
    if (self.httpWay==RequestMethodPost) {
        [dic setValue:@"application/x-www-form-urlencoded" forKey:@"Content-Type"];
    }
    [dic setValue:@"text/xml; charset=utf-8" forKey:@"Content-Type"];
    
    [dic setValue:[NSString stringWithFormat:@"%lu",(unsigned long)length] forKey:@"Content-Length"];
    
    [dic setValue:@"" forKey:@"SOAPAction"];
    
    NSLog(@"请求头为:%@",dic);
    return dic;
}

@end
